Popular Searches
Popular Course Categories
Popular Courses

Working with Parameters and Return Values

Working with Parameters and Return Values

Methods and Modular Programming

Working with Parameters and Return Values in Java

Course: Core Java Training

Topic: Working with Parameters and Return Values

Course Link: Core Java Training Course

Demo Link: Register for a Course Demo

JustAcademy Homepage: Visit JustAcademy


1. Introduction to Parameters and Return Values

In Java, methods help organize code into reusable blocks that perform specific tasks. Parameters allow a method to receive information, while return values allow it to send a result back to the code that called it.

For example, a method that calculates the total price of products may receive the quantity and price as parameters and return the calculated amount. This approach makes programs more modular, readable, reusable, and easier to test.

Parameters and return values are fundamental concepts used in calculations, data processing, object-oriented programming, application development, and problem-solving.

2. Learning Objectives

  • Understand the purpose of method parameters and arguments.
  • Learn how to declare methods with different parameter types.
  • Understand how return types define the results a method can provide.
  • Work with methods that return primitive values, objects, strings, and arrays.
  • Use multiple parameters and return values effectively.
  • Understand the role of the void keyword.
  • Apply parameters and return values to practical programming problems.
  • Identify common method declaration and return statement errors.

3. What Are Method Parameters?

A parameter is a variable declared inside a method's parentheses. It receives a value when the method is called and can be used within the method body.

Parameters allow a method to work with different inputs without requiring the code to be rewritten for every situation.

Example

public class ParameterExample {
    static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }

    public static void main(String[] args) {
        greet("Amit");
        greet("Priya");
    }
}

Output

Hello, Amit!
Hello, Priya!

In this example, name is the parameter. The method receives a different string each time it is called, allowing the same method to greet different people.

4. Parameters vs. Arguments

Parameters and arguments are related but refer to different parts of a method call.

Feature Parameters Arguments
Meaning Variables declared in a method definition. Values or expressions supplied when calling a method.
Location Method declaration. Method invocation.
Example int number 25
Purpose Receive input for the method. Provide the actual input value.

Example

static void displayNumber(int number) {
    System.out.println(number);
}

public static void main(String[] args) {
    displayNumber(25);
}

Here, number is the parameter and 25 is the argument.

5. Declaring Methods with Parameters

A method declaration can contain zero, one, or multiple parameters. Each parameter must have a data type and a name.

General Syntax

accessModifier static returnType methodName(dataType parameterName) {
    // Method body
}

The static keyword is optional and depends on whether the method belongs to the class or an object instance.

Example with One Parameter

public class SquareExample {
    static int square(int number) {
        return number * number;
    }

    public static void main(String[] args) {
        System.out.println(square(5));
    }
}

Output

25

The method accepts an integer and calculates its square. The result is returned to the caller.

6. Using Multiple Parameters

A method can accept multiple parameters when it needs more than one input. Each parameter must have its own declared type and name, and the arguments must match the parameter order and compatible types.

Example: Adding Two Numbers

public class AdditionExample {
    static int add(int first, int second) {
        return first + second;
    }

    public static void main(String[] args) {
        int result = add(15, 25);
        System.out.println("Sum: " + result);
    }
}

Output

Sum: 40

Explanation

  1. The method declares two integer parameters: first and second.
  2. The call add(15, 25) supplies two arguments.
  3. The method calculates their sum.
  4. The return statement sends the result back to the caller.
  5. The returned value is stored in the variable result.

7. What Is a Return Value?

A return value is the result a method sends back to the calling code. It allows a method to calculate information, process input, or produce an object that another part of the program can use.

The method's declared return type specifies the kind of value it can return.

Example

static double calculateArea(double length, double width) {
    return length * width;
}

This method returns a double value representing the area calculated from the length and width.

8. Understanding Return Types

The return type appears before the method name in a method declaration. It indicates the type of result that the method returns.

Return Type Description Example
int Returns an integer. return 100;
double Returns a decimal numeric value. return 19.75;
boolean Returns either true or false. return age >= 18;
char Returns a single character. return 'A';
String Returns a string reference. return "Java";
Class type Returns a reference to an object of a compatible type. return new Student();
Array type Returns a reference to an array. return new int[] {1, 2, 3};
void Indicates that the method does not return a value. static void printMessage()

9. Using the Return Statement

The return statement ends a method's execution and, for a non-void method, provides the value to send back to the caller.

Example

public class ReturnExample {
    static int getNumber() {
        return 50;
    }

    public static void main(String[] args) {
        int value = getNumber();
        System.out.println(value);
    }
}

Output

50

The method returns 50, which is assigned to value. A return statement may also appear in a conditional branch, provided every possible path in a non-void method returns a compatible value.

10. Methods That Return void

The void return type is used when a method performs an action without providing a result to the caller. Such methods may print messages, update object state, or perform other operations.

Example

public class VoidExample {
    static void showMessage() {
        System.out.println("Welcome to Core Java!");
    }

    public static void main(String[] args) {
        showMessage();
    }
}

Output

Welcome to Core Java!

A void method may use return; to exit early, but it cannot return a value such as an integer or string.

11. Returning Values from Conditional Statements

Methods can use conditional statements to determine which value to return. This is useful when the result depends on the supplied arguments.

Example: Finding the Larger Number

public class MaximumExample {
    static int findMaximum(int first, int second) {
        if (first > second) {
            return first;
        } else {
            return second;
        }
    }

    public static void main(String[] args) {
        System.out.println(findMaximum(45, 70));
    }
}

Output

70

Each branch returns an integer. Because both possible branches return a result, the method satisfies its declared int return type.

12. Returning Boolean Values

Boolean-returning methods are useful for validation, comparisons, eligibility checks, and decision-making. They return either true or false.

Example: Checking Voting Eligibility

public class EligibilityExample {
    static boolean isEligible(int age) {
        return age >= 18;
    }

    public static void main(String[] args) {
        System.out.println(isEligible(20));
        System.out.println(isEligible(16));
    }
}

Output

true
false

The method returns the result of the comparison directly, so a separate if-else statement is not necessary.

13. Returning String Values

A method can return a String when it needs to provide text to the caller. This is useful for creating messages, formatting labels, and converting data into readable output.

Example

public class StringReturnExample {
    static String createGreeting(String name) {
        return "Hello, " + name + "!";
    }

    public static void main(String[] args) {
        String message = createGreeting("Priya");
        System.out.println(message);
    }
}

Output

Hello, Priya!

The method creates and returns a string. The caller stores the returned reference in the variable message.

14. Returning Objects from Methods

Methods can return objects, allowing callers to receive a newly created object or an existing object reference. The declared return type must be compatible with the returned object.

Example

class Product {
    String name;
    double price;

    Product(String name, double price) {
        this.name = name;
        this.price = price;
    }
}

public class ObjectReturnExample {
    static Product createProduct() {
        return new Product("Keyboard", 1200.00);
    }

    public static void main(String[] args) {
        Product product = createProduct();

        System.out.println(product.name);
        System.out.println(product.price);
    }
}

Output

Keyboard
1200.0

The method returns a reference to a new Product object. The caller can use that reference to access the object's fields and methods.

15. Returning Arrays from Methods

A method can return an array when several values of the same type need to be provided together. The returned value is an array reference.

Example

import java.util.Arrays;

public class ArrayReturnExample {
    static int[] getNumbers() {
        return new int[] {10, 20, 30, 40};
    }

    public static void main(String[] args) {
        int[] numbers = getNumbers();
        System.out.println(Arrays.toString(numbers));
    }
}

Output

[10, 20, 30, 40]

Here, the method creates an integer array and returns its reference. The caller assigns that reference to numbers.

16. Combining Parameters and Return Values

Parameters and return values are commonly used together. A method receives the required inputs, performs a calculation or operation, and returns the result.

Example: Calculating a Discounted Price

public class DiscountExample {
    static double calculateDiscountedPrice(
            double price, double discountPercent) {

        double discount = price * discountPercent / 100;
        return price - discount;
    }

    public static void main(String[] args) {
        double finalPrice = calculateDiscountedPrice(2000, 10);
        System.out.println("Final price: " + finalPrice);
    }
}

Output

Final price: 1800.0

Explanation

  1. The method accepts the original price and discount percentage.
  2. It calculates the discount amount.
  3. It subtracts the discount from the original price.
  4. It returns the final price.
  5. The calling code stores and displays the returned result.

17. Understanding Pass-by-Value with Parameters

Java always passes arguments by value. For primitive arguments, the copied value is the primitive itself. For object arguments, the copied value is the object reference.

Therefore, assigning a new value to a primitive parameter does not change the caller's primitive variable. Similarly, reassigning an object parameter does not replace the caller's reference. However, a method can modify a mutable object's state through the copied reference.

Example

public class PassByValueExample {
    static void changeNumber(int number) {
        number = 99;
    }

    public static void main(String[] args) {
        int value = 10;

        changeNumber(value);

        System.out.println(value);
    }
}

Output

10

The parameter number is a separate local variable. To communicate a calculated primitive value back to the caller, return it and assign the result.

18. Calling a Method and Using Its Return Value

A method's returned value can be used in several ways, depending on the return type and the requirements of the program.

  • Store the result: int result = add(5, 10);
  • Print the result: System.out.println(add(5, 10));
  • Use it in an expression: int total = add(5, 10) * 2;
  • Pass it to another method: display(add(5, 10));
  • Use it in a condition: if (isEligible(20)) { ... }

Example

public class ReturnUsageExample {
    static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        int result = add(5, 10);
        System.out.println("Stored result: " + result);
        System.out.println("Direct result: " + add(20, 30));
        System.out.println("Expression result: " + (add(2, 3) * 2));
    }
}

Output

Stored result: 15
Direct result: 50
Expression result: 10

19. Common Rules for Parameters and Return Values

  • Each parameter in a method declaration must have a type and a name.
  • Arguments supplied in a method call must match the number and order of parameters, with compatible types.
  • A non-void method must return a value compatible with its declared return type on every possible path.
  • A void method cannot return a value.
  • A return statement immediately ends the current method execution.
  • A method may return a primitive value or a reference to an object or array.
  • Java does not allow a method to return multiple independent values directly, but it can return an object, an array, or a collection containing multiple values.
  • Method parameters are local to the method and cannot be accessed directly outside its scope.

20. Common Errors and Troubleshooting

Error Cause Solution
Missing return statement A non-void method has a possible execution path without a return value. Ensure every possible path returns a compatible value.
Incompatible return type The returned expression does not match the declared return type. Return a compatible value or correct the method's return type.
Cannot return a value from a void method A value is returned from a method declared with void. Change the return type or remove the returned value.
Wrong number of arguments The method call does not supply the required arguments. Check the method declaration and pass the correct number of arguments.
Argument type mismatch An argument cannot be converted to the required parameter type. Pass a compatible value or use an appropriate conversion.
Unreachable code after return A statement is placed after a return statement in the same execution path. Move the statement before the return or restructure the method.
Unexpected original variable value The code assumes that changing a parameter changes the caller's variable. Remember pass-by-value and return the updated result when needed.

21. Best Practices

  • Give methods descriptive names that explain their purpose.
  • Use parameters to supply the information a method needs instead of relying on unnecessary global state.
  • Choose a return type that accurately represents the result.
  • Keep each method focused on one clear responsibility.
  • Use void for actions that do not need to return a result.
  • Return calculated values rather than relying on changes to local primitive parameters.
  • Validate inputs when methods have requirements or constraints.
  • Use meaningful parameter names such as quantity, unitPrice, and discountPercent.
  • Avoid confusing side effects when a method is expected only to calculate and return a result.
  • Write unit tests for important input combinations, including boundary cases.

22. Practical Mini Project: Student Result Calculator

Build a small Java program that accepts a student's marks, calculates the total and average, and returns a result message. This project demonstrates multiple parameters, numeric return values, and String return values.

Program

public class StudentResultCalculator {
    static int calculateTotal(int mark1, int mark2, int mark3) {
        return mark1 + mark2 + mark3;
    }

    static double calculateAverage(int total, int subjects) {
        if (subjects <= 0) {
            throw new IllegalArgumentException(
                "Number of subjects must be positive."
            );
        }
        return (double) total / subjects;
    }

    static String getResult(double average) {
        if (average >= 40) {
            return "Pass";
        }
        return "Needs Improvement";
    }

    public static void main(String[] args) {
        int total = calculateTotal(75, 80, 65);
        double average = calculateAverage(total, 3);
        String result = getResult(average);

        System.out.println("Total: " + total);
        System.out.println("Average: " + average);
        System.out.println("Result: " + result);
    }
}

Output

Total: 220
Average: 73.33333333333333
Result: Pass

Project Explanation

  1. calculateTotal() accepts three marks and returns their sum.
  2. calculateAverage() accepts the total and number of subjects, validates the subject count, and returns a decimal average.
  3. getResult() accepts the average and returns a text result.
  4. The main() method calls these methods and uses each returned value in the next calculation.

23. Practice Exercises

Exercise 1: Area Calculator

Write a method named calculateArea() that accepts a rectangle's length and width and returns its area.

Exercise 2: Even or Odd

Create a method named isEven() that accepts an integer and returns a boolean indicating whether it is even.

Exercise 3: Temperature Conversion

Write a method that accepts a temperature in Celsius and returns the Fahrenheit equivalent using the formula F = (C * 9 / 5) + 32. Use floating-point arithmetic to preserve decimal results.

Exercise 4: Employee Salary

Create a method that accepts a basic salary and an allowance and returns the total salary.

Exercise 5: Full Name

Write a method that accepts a first name and last name and returns the combined full name.

Exercise 6: Maximum of Three Numbers

Create a method that accepts three integers and returns the largest number.

Exercise 7: Array Statistics

Write a method that accepts an integer array and returns the sum of its elements. Consider how the method should handle an empty array.

24. Interview Questions and Answers

Q1. What is a parameter in Java?

Answer: A parameter is a variable declared in a method definition that receives an argument when the method is called.

Q2. What is an argument?

Answer: An argument is the actual value or expression supplied to a method during a method call.

Q3. What is a return value?

Answer: A return value is the result a method sends back to the calling code through a return statement.

Q4. What is the purpose of the void keyword?

Answer: The void keyword indicates that a method does not return a value.

Q5. Can a method return a String or an object?

Answer: Yes. A method can return a String, an object reference, an array reference, a primitive value, or another compatible type.

Q6. Can a Java method return multiple values directly?

Answer: A method has one declared return type and returns one value per invocation. To represent multiple results, it can return an object, array, or collection containing them.

Q7. What happens when a return statement executes?

Answer: The current method execution ends immediately. For a non-void method, the specified value is returned to the caller.

Q8. Can a method have multiple parameters?

Answer: Yes. A method can declare multiple parameters separated by commas, and the method call must provide compatible arguments in the corresponding order.

Q9. Can a void method use a return statement?

Answer: Yes. It can use return; without a value to exit early, but it cannot return a value.

Q10. What is the difference between a parameter and a return value?

Answer: A parameter supplies input to a method, while a return value supplies output from the method to its caller.

Q11. What happens if a non-void method does not return a value on every possible path?

Answer: Java reports a compile-time error when it determines that the method can finish without returning a compatible value.

Q12. Why are parameters and return values useful?

Answer: They help make code reusable, modular, testable, easier to maintain, and less dependent on shared mutable state.

25. Quick Revision Checklist

  • Parameters are declared in method definitions.
  • Arguments are supplied when methods are called.
  • Return types specify the type of result a method provides.
  • The return statement ends method execution and may return a value.
  • The void keyword indicates that no value is returned.
  • Methods can return primitives, strings, objects, and arrays.
  • Java passes arguments by value, including copied object reference values.
  • Non-void methods must return compatible values along every possible execution path.
  • Returned values can be stored, printed, passed to other methods, or used in expressions.
  • Clear method names and focused responsibilities improve maintainability.

26. Conclusion

Parameters and return values are essential building blocks of Java methods. Parameters allow methods to receive input, while return values allow them to communicate results back to the caller. Together, they support reusable, organized, and maintainable programs.

By practicing methods with primitive values, strings, objects, arrays, conditional logic, and multiple parameters, learners can build a strong foundation for more advanced Core Java concepts and application development.

Continue learning with the Core Java Training Course, register for a course demo, or explore more learning resources on the JustAcademy homepage.

whatsapp